package com.feri.fs.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feri.fs.provider.core.AliOssUtils;
import com.feri.fs.provider.core.CodeGenUtils;
import com.feri.fs.provider.dao.ProjectsrcDao;
import com.feri.fs.provider.dao.UserProjectDao;
import com.feri.fs.provider.entity.ProjectSrc;
import com.feri.fs.provider.entity.UserProject;
import com.feri.fs.provider.service.intf.UserProjectService;
import common.bo.UserProjectBo;
import common.utils.BeanUtil;
import common.utils.StringUtils;
import common.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class UserProjectServiceImpl implements UserProjectService {
    @Autowired
    private UserProjectDao dao;
    @Autowired
    private ProjectsrcDao projectsrcDao;

    @Override
    @Transactional//开启事务
    public R save(UserProjectBo bo) {
        if (bo!=null){
            if (StringUtils.isNotEmpty(bo.getDburl(),bo.getDbuser(),bo.getDbpass(),bo.getPkname())){
                //生成源码并上传OSS
                String objName=bo.getPname()+"_"+System.currentTimeMillis()+".zip";
                Date etime= CodeGenUtils.getTime(1);
                String url=CodeGenUtils.createCodeZip(bo,objName,etime);
                //验证结果
                if (StringUtils.isNotEmpty(url)){
                    //成功，就需要添加数据
                    UserProject project= BeanUtil.copyProperty(UserProject.class,bo,bo.getClass().getDeclaredFields());
                    project.setCtime(new Date());
                    //敏感数据加密，略。
                    dao.insert(project);
                    ProjectSrc projectSrc=new ProjectSrc();
                    projectSrc.setBname(AliOssUtils.bucketName);
                    projectSrc.setObjname(objName);
                    projectSrc.setSrcurl(url);
                    projectSrc.setCtime(new Date());
                    projectSrc.setEtime(etime);
                    projectSrc.setPid(project.getId());
                    projectsrcDao.insert(projectSrc);
                    //返回结果
                    return R.ok(url);
                }
            }
        }
        return R.fail("新增失败");
    }

    @Override
    public R queryById(int id) {
        if(id>0){
            return R.ok(dao.selectById(id));
        }
        return R.fail("请传递参数！");
    }

    @Override
    public R queryPage(int page, int size) {
        Page<UserProject> projectPage=new Page<>(page,size);
        return R.ok(dao.selectPage(projectPage,new QueryWrapper<UserProject>().orderByDesc("id")));
    }

    @Override
    public R queryDetail(int id) {
        if (id>0){
            return R.ok(dao.selectId(id));
        }

        return R.fail("请传递参数！");
    }
}
